// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import ItemGrid from '../items/ItemGrid';
import { gameData } from '../tool/GameData';

const { ccclass, property } = cc._decorator;

const archiveText = ['身体健康吃嘛嘛香', '勤勤恳恳打工人', '财运亨通飞黄腾达', '家庭幸福儿女双全', '好好学习天天向上'];

@ccclass
export default class UIManager extends cc.Component {
  @property(cc.Sprite)
  private activeSprites: cc.Sprite[] = [];

  @property(ItemGrid)
  private itemGrids: ItemGrid[] = [];

  @property(cc.Label)
  private descriptionLabel: cc.Label = null;

  // LIFE-CYCLE CALLBACKS:

  // onLoad () {}

  private focusIndex = -1;
  start() {
    this.activeSprites.forEach((s) => (s.enabled = false));
  }

  update() {
    if (!gameData.myPlayer) {
      return;
    }
    const uiFocusIndex = gameData.myPlayer.uiFocusIndex;
    if (this.focusIndex !== uiFocusIndex) {
      // 更新 ui focus
      const lastSprite = this.activeSprites[this.focusIndex];
      const currentSprite = this.activeSprites[uiFocusIndex];

      if (lastSprite) {
        lastSprite.enabled = false;
      }
      if (currentSprite) {
        currentSprite.enabled = true;
      }
      this.focusIndex = uiFocusIndex;
      requestAnimationFrame(() => {
        this.setDesription(uiFocusIndex);
      });
    }

    const items = gameData.myPlayer.items;
    for (let i = 0, len = items.length; i < len; i++) {
      const item = items[i];
      this.itemGrids[i].setItem(item);
    }
  }

  private setDesription(uiIndex: number) {
    if (uiIndex < 5) {
      const item = this.itemGrids[uiIndex];
      if (item.currentItem) {
        this.descriptionLabel.string = item.currentItem.description;
      } else {
        this.descriptionLabel.string = '';
      }
    } else if (uiIndex >= 8 && uiIndex <= 12) {
      const achiveIndex = uiIndex - 8;
      const text = archiveText[achiveIndex];
      this.descriptionLabel.string = text;
    }
  }
}
